import { potentiallyParseOpenApiString } from './parseOpenApiString.js';
export const getOpenApiOperationMethodAndEndpoint = (endpointStr, openApiFiles) => {
    var _a;
    const potentiallyParsedOpenApiString = potentiallyParseOpenApiString(endpointStr);
    if (potentiallyParsedOpenApiString == undefined) {
        return undefined;
    }
    const { endpoint, method, filename } = potentiallyParsedOpenApiString;
    let path = undefined;
    let apiFile = undefined;
    for (const file of openApiFiles) {
        const openApiFile = file.spec;
        const openApiPath = (_a = openApiFile.paths) === null || _a === void 0 ? void 0 : _a[endpoint];
        const isFilenameOrNone = !filename || filename === file.filename;
        if (openApiPath && isFilenameOrNone) {
            path = openApiPath;
            apiFile = openApiFile;
        }
    }
    if (path == null || apiFile == null) {
        return undefined;
    }
    const operationResponse = getOperation(method, path);
    if (operationResponse == null) {
        return undefined;
    }
    const { method: finalMethod, operation } = operationResponse;
    return {
        method: finalMethod,
        endpoint,
        operation,
        path,
    };
};
const getOperation = (method, pathObject) => {
    const methods = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'];
    if (method !== undefined) {
        const lowerMethod = method.toLowerCase();
        if (methods.includes(lowerMethod) && lowerMethod in pathObject) {
            return {
                method: lowerMethod,
                operation: pathObject[lowerMethod],
            };
        }
    }
    else {
        for (const method of methods) {
            if (method in pathObject) {
                return {
                    method,
                    operation: pathObject[method],
                };
            }
        }
    }
    return undefined;
};
